//
//  JKFileExplorerManager.m
//  TestCocoaHTTPserver
//
//  Created by albert on 2018/11/8.
//  Copyright © 2018 albert. All rights reserved.
//

#import "JKFileExplorerManager.h"
#import "JKFileExplorerViewController.h"
#import "JKFileExplorerEngine.h"
#import "JKFileManager.h"

@interface JKFileExplorerManager ()

@end

/** 当前被prsented的导航控制器数组 */
//static NSMutableArray *currentPresentedNavArr_;

@implementation JKFileExplorerManager

static NSString *myFilesDirectoryName;

+ (void)initializeWithAirDropFolderName:(NSString *)folderName{
    
    NSString *name = [folderName stringByTrimmingCharactersInSet:
                      [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (name != nil &&
        ![name isEqualToString:@""]) {
        
        myFilesDirectoryName = name;
    }
    
    [self createMyFilesDirectory];
}

//+ (NSMutableArray *)currentPresentedNavArr{
//    if (!currentPresentedNavArr_) {
//        currentPresentedNavArr_ = [NSMutableArray array];
//    }
//    return currentPresentedNavArr_;
//}

+ (void)handleOpenURL:(NSURL *)URL{
    
    if (![URL isFileURL]) { return; }
    
    [self handleAirDropWithURL:URL];
}

+ (void)handleAirDropWithURL:(NSURL *)URL{
    
    NSString *filePath = [URL path];
    
    NSString *fileName = filePath.lastPathComponent;
    
    // 获取自己的文件夹路径
    NSString *myFilesDirectory = [self myFilesDirectory];
    
    // 要移动到的路径
    NSString *destinationFilePath = [myFilesDirectory stringByAppendingPathComponent:fileName];
    
    BOOL shouldCreate = [self checkShouldCreateMyFilesDirectory];
    
    if ([JKFileManager isExistsAtPath:filePath]) { // 文件存在
        
        if ([self createMyFilesDirectory]) {
            
            if (shouldCreate) {
                
                // 先发一个通知，告诉已存在的JKFileExplorerViewController有新目录被创建
                [[NSNotificationCenter defaultCenter] postNotificationName:JKFileExplorerDidAddFileNotification object:nil userInfo:myFilesDirectory ? @{JKFileExplorerFileOperateDestinationFilePathsKey : myFilesDirectory} : nil];
                
                // 延时执行
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    // 移动到自己的文件夹中
                    [self moveFilePath:filePath toFilePath:destinationFilePath];
                });
                
            } else {
                
                // 移动到自己的文件夹中
                [self moveFilePath:filePath toFilePath:destinationFilePath];
            }
            
        } else {
            
            // 跳转到系统的Inbox文件夹
            [self jumptoSystemInboxDirectoryWithFilePath:filePath];
        }
        
    } else { // 收到文件不存在
        
        NSLog(@"收到文件不存在: ->%@<-", URL);
    }
}

+ (BOOL)createMyFilesDirectory{
    
    BOOL isDirectory = NO;
    
    BOOL isExist = [JKFileManager isExistsAtPath:[self myFilesDirectory] isDirectory:&isDirectory];
    
    if (isExist) {
        
        if (isDirectory) { return YES; }
        
        return [self solveCreateMyFilesDirectoryDuplication];
    }
    
    return [self createDirectoryAtPath:[self myFilesDirectory]];
}

+ (BOOL)checkShouldCreateMyFilesDirectory{
    
    BOOL isDirectory = NO;
    
    BOOL isExist = [JKFileManager isExistsAtPath:[self myFilesDirectory] isDirectory:&isDirectory];
    
    return (!isExist || !isDirectory);
}

+ (BOOL)solveCreateMyFilesDirectoryDuplication{
    
    // 时间戳
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    
    NSString *timeStampStr = @(timeStamp).stringValue;
    
    NSString *toPath = [JKFileExplorerEngine checkDuplicationNameWithFilePath:[[[self myFilesDirectory] stringByAppendingString:@"_backup_"] stringByAppendingString:timeStampStr ? timeStampStr : @"0"] isFolder:NO];
    
    NSError *error = nil;
    
    BOOL success =  [JKFileManager moveItemAtPath:[self myFilesDirectory] toPath:toPath error:&error];
    
    if (error || !success) { return NO; }
    
    return [self createDirectoryAtPath:[self myFilesDirectory]];
}

+ (BOOL)createDirectoryAtPath:(NSString *)path{
    
    NSError *error;
    
    BOOL success = [JKFileManager createDirectoryAtPath:path error:&error];
    
    if (error || !success) { // 创建文件夹出错
        
        NSLog(@"创建文件夹出错: %@", error.localizedDescription);
        
        return NO;
    }
    
    return YES;
}

+ (void)moveFilePath:(NSString *)filePath toFilePath:(NSString *)toFilePath{
    
    if (!toFilePath || [toFilePath isEqualToString:@""]) {
        
        // 跳转到系统的Inbox文件夹
        
        [self jumptoSystemInboxDirectoryWithFilePath:filePath];
        
        return;
    }
    
    NSError *error;
    
    // 检查重名
    NSString *destinationPath = [JKFileExplorerEngine checkDuplicationNameWithFilePath:toFilePath sourceFilePath:filePath];
    
    if (![destinationPath isEqualToString:toFilePath]) {
        
        NSLog(@"移动文件目标位置已存在，文件名由%@更改为%@", [toFilePath lastPathComponent], [destinationPath lastPathComponent]);
    }
    
    BOOL success = [JKFileManager moveItemAtPath:filePath toPath:destinationPath overwrite:NO error:&error];
    
    if (error || !success) { // 移动文件出错
        
        NSLog(@"移动文件出错: %@", error.localizedDescription);
        
        // 跳转到系统的Inbox文件夹
        
        [self jumptoSystemInboxDirectoryWithFilePath:filePath];
        
        return;
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 移动文件成功，跳转自己文件夹
        [self jumptoMyFilesDirectoryWithPath:destinationPath];
    });
}

+ (void)jumptoSystemInboxDirectoryWithFilePath:(NSString *)filePath{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self jumptoMyFilesDirectoryWithPath:filePath];
    });
}

+ (void)jumptoMyFilesDirectoryWithPath:(NSString *)filePath{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKFileExplorerDidAddFileNotification object:nil userInfo:filePath ? @{JKFileExplorerFileOperateDestinationFilePathsKey : filePath} : nil];
    
    UIViewController *viewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    
    while (viewController.presentedViewController) {
        
        viewController = viewController.presentedViewController;
    }
    
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        
        viewController = [(UINavigationController *)viewController topViewController];
    }
    
    if ([viewController isKindOfClass:[JKFileExplorerViewController class]]) {
        
        NSString *currentDirectory = [(JKFileExplorerViewController *)viewController currentDirectory];
        
        if ([[currentDirectory stringByAppendingPathComponent:filePath.lastPathComponent] isEqualToString:filePath]) {
            
            return;
        }
    }
    
    JKFileExplorerViewController *vc = [[JKFileExplorerViewController alloc] init];
    vc.fileNewItemPath = filePath;
    vc.isRootViewController = YES;
    vc.directoryPath = [self myFilesDirectory];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    nav.interactivePopGestureRecognizer.delegate = nil;
    
    [viewController presentViewController:nav animated:YES completion:nil];
    
    NSLog(@"弹出新vc-->%@ nav-->%@", vc, nav);
}

+ (NSString *)myFilesDirectoryName{
    
    if (!myFilesDirectoryName) {
        
        myFilesDirectoryName = @"MyFiles";
    }
    
    return myFilesDirectoryName;
}

+ (NSString *)myFilesDirectory{
    
    static NSString *myFilesDirectory;
    
    if (!myFilesDirectory) {
        
        NSString *documentsDirectory = [JKFileManager documentsDirectory];
        
        NSString *myFilesDirectoryName = [self myFilesDirectoryName];
        
        myFilesDirectory = [documentsDirectory stringByAppendingPathComponent:myFilesDirectoryName];
    }
    
    return myFilesDirectory;
}

+ (NSString *)systemInboxDirectory{
    
    static NSString *systemInboxDirectory;
    
    if (!systemInboxDirectory) {
        
        NSString *documentsDirectory = [JKFileManager documentsDirectory];
        
        NSString *inboxDirectoryName = @"Inbox";
        
        systemInboxDirectory = [documentsDirectory stringByAppendingPathComponent:inboxDirectoryName];
    }
    
    return systemInboxDirectory;
}

+ (void)showWithViewController:(UIViewController *)viewController{
    
    JKFileExplorerSortConfig sortConfig = {0, 0, 0};
    
    [self showWithDirectory:NSHomeDirectory() sortConfig:sortConfig viewController:viewController];
}

+ (void)showWithDirectory:(NSString *)directory
           viewController:(UIViewController *)viewController{
    
    JKFileExplorerSortConfig sortConfig = {0, 0, 0};
    
    [self showWithDirectory:directory sortConfig:sortConfig viewController:viewController];
}

+ (void)showWithDirectory:(NSString *)directory
               sortConfig:(JKFileExplorerSortConfig)sortConfig
           viewController:(UIViewController *)viewController{
    
    JKFileExplorerViewController *vc = [[JKFileExplorerViewController alloc] init];
    vc.directoryPath = directory;
    vc.isRootViewController = YES;
    vc.sortConfig = sortConfig;
    
    if ([directory isEqualToString:@"/"]) {
        
        vc.navTitle = @"根目录";
    }
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    nav.interactivePopGestureRecognizer.delegate = nil;
    
    if (viewController && [viewController isKindOfClass:[UIViewController class]]) {
        
        [viewController presentViewController:nav animated:YES completion:nil];
        
        return;
    }
    
    UIViewController *rootVC = [UIApplication sharedApplication].delegate.window.rootViewController;
    
    while (rootVC.presentedViewController) {
        
        rootVC = viewController.presentedViewController;
    }
    
    [rootVC presentViewController:nav animated:YES completion:nil];
}
@end
